<!--审批意见，审批按钮-->
<template>
  <div class='home' style="margin-top: 15px;">
    <el-form ref="beanForm" :model="beanForm" size="mini">
      <el-row v-if="showOpinion">
        <!--审批意见-->
        <el-col :xs="24" :sm="12" :md="12">
          <el-form-item label="审批意见" prop="opinion" :rules="formRules.opinion" label-width="100px">
            <el-input type="textarea" v-model="beanForm.opinion"></el-input>
          </el-form-item>
        </el-col>
        <!--选择驳回节点-->
        <el-col v-show="showRejectTask" :xs="24" :sm="12" :md="12">
          <el-form-item label="选择驳回节点" prop="rejectTask" :rules="formRules.rejectTask" label-width="120px">
            <el-select
              v-model="beanForm.rejectTask"
              placeholder="请选择驳回节点"
              filterable
              clearable
            >
              <el-option
                v-for="item in dict.rejectTask"
                :key="item.id"
                :label="item.text"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <div style="text-align: center;">
        <el-button v-show="showSubmit" type="success" plain @click="submitClick" size="mini">提交</el-button>
        <el-button v-show="showRefuse" type="danger" @click="refuseClick" size="mini">拒绝</el-button>
        <el-button v-show="showReject" type="warning" @click="rejectClick" size="mini">驳回</el-button>
        <el-button v-show="showPass" type="success" @click="passClick" size="mini">通过</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
  /* ajax请求 */
  import * as kk from '../../../../utils/k-utils'

  export default {
    name: 'FormOpinionBtns',
    props: {
      // 保存列表页面传过来的数据，子组件接受父组件数据
      param: {
        type: Object,
        required: true
      }
    },
    data() {
      return {
        /* 字典 */
        dict: {
          rejectTask: [] // 选择驳回节点
        },
        beanForm: {
          opinion: '', // 审批意见
          rejectTask: '' // 选择驳回节点
        },
        formRules: {
          opinion: [
            { required: true, message: '请输入审批意见', trigger: 'blur' }
          ],
          rejectTask: [
            { required: true, message: '请选择驳回节点', trigger: 'change' }
          ]
        },
        first: true, // 是否第一次打开组件
        showRejectTask: false, // 驳回到那个节点
        showOpinion: true, // 是否显示审批意见
        showSubmit: false, // 提交按钮是否显示 0
        showRefuse: false, // 拒绝按钮是否显示 1
        showReject: false, // 驳回按钮是否显示 2
        showPass: false // 通过按钮是否显示 3
      }
    },
    // 执行一次，且第一次执行
    mounted() {
      this.init()
      this.first = true
    },
    // 组件被激活，第一次不执行
    activated() {
      // this.param父组件改变该属性值
      if (this.first) {
        this.first = false
        return
      }
      // 清空数据显示按钮
      this.search(this.param)
    },
    methods: {
      init() {
        this.search(this.param)
        this.first = true
      },
      // 查询数据
      search(requestSupportParams) {
        this.beanForm.opinion = '' // 审批意见
        // 是否有驳回节点，去除校验
        this.formRules.rejectTask = []
        // 这里是流程开始页面加载
        if (requestSupportParams.method === 'start') {
          this.renderFormOpinionBtns('0')// 渲染开始按钮
          this.showOpinion = false// 审批意见不显示
        } else {
          var _this = this
          // 查询选择的按钮
          var url = '/conf/getTaskBtns.json?processId=' + requestSupportParams.processId
          kk.k_load_url('workflow', url, {}).then(rep => {
            rep = JSON.parse(rep)
            if (rep['status'] === '200') {
              // 第0个为默认。
              var btnsConf = rep.data
              var btns = ''
              // 获取对应的任务的按钮
              for (var i = 1; i < btnsConf.length; i++) {
                var btnConf = btnsConf[i]
                if (btnConf.taskName === requestSupportParams.taskName) {
                  btns = btnConf.btns
                }
              }
              _this.renderFormOpinionBtns(btns)// 渲染开始按钮
            } else {
              _this.$message(rep.message)
            }
          })
        }
      },
      // 按钮显示
      renderFormOpinionBtns(btns) {
        btns = btns.split(',')
        this.showSubmit = btns.indexOf('0') !== -1// 有提交按钮
        this.showRefuse = btns.indexOf('1') !== -1// 拒绝
        this.showReject = btns.indexOf('2') !== -1// 驳回
        this.showPass = btns.indexOf('3') !== -1// 通过
      },
      // ------------------------------公共函数------------------------------
      // 将obj1对象的数据拷贝到obj2对象
      copyObj(obj1, obj2) {
        for (var key in obj1) {
          // 原型对象不拷贝
          if (key === '__proto__') {
            continue
          }
          // 自动将number转换成string
          if (typeof obj1[key] === 'number') {
            obj1[key] = '' + obj1[key]
          }
          obj2[key] = obj1[key]
        }
      },
      // 数组通过属性查找 例如 arr = [obj,obj]
      findWhere(arr, obj) {
        for (var i = 0; i < arr.length; i++) {
          for (var key in obj) {
            // key相等,value也相等
            if (arr[i].hasOwnProperty(key) && arr[i][key] === obj[key]) {
              return arr[i]
            }
          }
        }
        return {}
      },
      // ------------------------------审批按钮------------------------------
      // 提交
      submitClick() {
        var submitParams = {}
        this.copyObj(this.beanForm, submitParams)
        var requestSupportParams = this.param
        var _this = this
        this.$confirm('确认发起自定义流程?', '提示', {})
          .then(() => {
            // 校验数据
            // 提交数据
            kk.k_load_url('workflow', '/processInstance/startAndExecute.json', {
              'submitParams': JSON.stringify(submitParams),
              'processName': requestSupportParams.processName,
              'controllerClass': 'com.kayak.cloud.workflow.busi.ControllerClass',
              'controllerMethod': 'controllerMethod'
            }).then(rep => {
              rep = JSON.parse(rep)
              if (rep['status'] === '500') {
                _this.$message(rep.message)
              } else {
                _this.$message('自定义流程开启成功')
              }
            })
          })
          .catch(() => { /* 用户取消注销 */ })
      },
      // 拒绝
      refuseClick() {
        // 检验数据
        var _this = this
        this.$refs['beanForm'].validate((valid) => {
          if (valid) {
            _this.refuseClick_confirm(_this.param)
          } else {
            console.log('表单数据检验没有全部通过！！')
          }
        })
      },
      // 拒绝-确认弹出框
      refuseClick_confirm(requestSupportParams) {
        var _this = this
        this.$confirm('确认拒绝?', '提示', {})
          .then(() => {
            var dataToSubmit = {
              opinion: _this.beanForm.opinion,
              result: window.processStatusConstant.refuse,
              taskId: requestSupportParams.taskId,
              isSurrogate: requestSupportParams.isSurrogate
            }
            // 附件处理
            _this.send_audit(dataToSubmit)
          })
          .catch(() => { /* 用户取消注销 */ })
      },
      // 驳回
      rejectClick(requestSupportParams) {
        // 检验数据
        var _this = this
        this.$refs['beanForm'].validate((valid) => {
          if (valid) {
            _this.rejectClick_confirm(_this.param)
          } else {
            console.log('表单数据检验没有全部通过！！')
          }
        })
      },
      // 驳回-确认弹出框
      rejectClick_confirm(requestSupportParams) {
        var _this = this
        var dataToSubmit = {}
        dataToSubmit.opinion = this.beanForm.opinion
        this.$confirm('确认驳回?', '提示', {})
          .then(() => {
            // 是否驳回到上一个节点
            if (_this.beanForm.rejectTask) {
              dataToSubmit.resultText = '【' + kk.getParameterByName('taskDisplayName') + '】'
              dataToSubmit.resultText += '驳回到【' + _this.findWhere(this.dict.rejectTask, { id: _this.beanForm.rejectTask }) + '】'
              dataToSubmit.taskName = _this.beanForm.rejectTask
            } else {
              dataToSubmit.resultText = '【' + kk.getParameterByName('taskDisplayName') + '】'
              dataToSubmit.resultText += '驳回到【上一个节点】'
            }
            dataToSubmit.result = window.processStatusConstant.reject
            dataToSubmit.taskId = requestSupportParams.taskId
            // 判断是否为代理
            dataToSubmit.isSurrogate = requestSupportParams.isSurrogate
            _this.send_audit(dataToSubmit)
          })
          .catch(() => { /* 用户取消注销 */ })
      },
      // 通过
      passClick() {
        // 检验数据
        var _this = this
        this.$refs['beanForm'].validate((valid) => {
          if (valid) {
            _this.passClick_confirm(_this.param)
          } else {
            console.log('表单数据检验没有全部通过！！')
          }
        })
      },
      // 通过-确认弹出框
      passClick_confirm(requestSupportParams) {
        var _this = this
        this.$confirm('确认通过?', '提示', {})
          .then(() => {
            var dataToSubmit = {
              opinion: _this.beanForm.opinion,
              result: window.processStatusConstant.pass,
              taskId: requestSupportParams.taskId,
              isSurrogate: requestSupportParams.isSurrogate
            }
            // 附件处理
            _this.send_audit(dataToSubmit)
          })
          .catch(() => { /* 用户取消注销 */ })
      },
      // 将审批结果保存
      send_audit(dataToSubmit) {
        var _this = this
        kk.k_load_url('workflow', '/approval/doApproval.json', dataToSubmit).then(rep => {
          rep = JSON.parse(rep)
          if (rep['status'] === '200') {
            if (!window.embbedWfPage) {
              _this.$message('审核成功')
            }
            // 关闭当前页面
            kk.k_close_self_page()
          } else {
            if (rep.message) {
              _this.$message(rep.message)
            } else {
              _this.$message('审核失败')
            }
          }
        })
      }
    }
  }
</script>

<style scoped>
  /*让文本可以被选中*/
  .home {
    -moz-user-select: text; /*火狐*/
    -webkit-user-select: text; /*webkit浏览器*/
    -ms-user-select: text; /*IE10*/
    -khtml-user-select: text; /*早期浏览器*/
    user-select: text;
  }
  .wf_h {
    font-size: 18px;
    font-family: inherit;
    font-weight: 500;
    line-height: 1.1;
    color: inherit;
  }
</style>
